package icasue.runninginvoke.task.reader;

import org.springframework.util.Assert;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2020/11/9 下午8:01
 * @UpdateDate:
 * @Description:
 */
public class FileReadUtil {

    public static <T> String readClassPathFile(String classPath){
        Assert.notNull(classPath,"Can't read a 'null' classpath resource.");
        InputStream parkStyleStream = null;
        try {
            parkStyleStream = FileReadUtil.class.getClassLoader().getResourceAsStream(classPath);
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(parkStyleStream, "utf-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            return responseStrBuilder.toString();
        }catch (Throwable e){
            throw new RuntimeException("Class path file ["+classPath+"] read occur an error, check file if exist pls.",e.getCause());
        } finally {
            synchronized (FileReadUtil.class) {
                if (parkStyleStream != null) {
                    try {
                        parkStyleStream.close();
                    } catch (IOException e) { }
                }
            }
        }
    }

}
